# -*- coding: utf-8 -*-
import os
import uuid
import platform
from datetime import datetime

from flask import request, render_template, session
from flask_sqlalchemy import SQLAlchemy
from werkzeug.utils import secure_filename

# 兼容系统目录分割符
from WEB.app.Decorator import Logger
from WEB.app.Decorator.Login import pc_login_required, pc_admin_login_required
from WEB.app import app, settings
from WEB.app.models import UploadLog

if platform.system() == "Windows":
    slash = '\\'
elif platform.system() == "Linux":
    slash = '/'
else:
    slash = '/'

# 基础数据 赋值
from WEB.app.settings import WEB_PB

now_time = datetime.now()
now_date = str(now_time.year) + str(now_time.month) + str(now_time.day)
UPLOAD_FOLDER = WEB_PB + slash + 'upload' + slash + now_date
ADMIN_UPLOAD_FOLDER = WEB_PB + slash + 'upload' + slash + 'admin' + slash + now_date
ALLOW_EXTENSIONS = {'html', 'htm', 'doc', 'docx', 'mht', 'pdf', 'txt'}

# 判断文件夹是否存在，如果不存在则创建
if not os.path.exists(UPLOAD_FOLDER):
    os.makedirs(UPLOAD_FOLDER)
if not os.path.exists(ADMIN_UPLOAD_FOLDER):
    os.makedirs(ADMIN_UPLOAD_FOLDER)


# 判断文件后缀是否在列表中
def allowed_file(filename):
    return '.' in filename and \
           filename.rsplit('.', 1)[1] in ALLOW_EXTENSIONS


@pc_admin_login_required
def admin_upload_file():
    """
    后台导入文件
    :return:
    """

    class Params():
        msg = None
        file_path = None
        is_success = False

    params = Params()

    if request.method == 'POST':
        # 获取post过来的文件名称，从name=file参数中获取
        file = request.files['file']
        if file and allowed_file(file.filename):
            # secure_filename方法会去掉文件名中的中文
            filename = secure_filename(file.filename)
            # 因为上次的文件可能有重名，因此使用uuid保存文件
            file_name = str(uuid.uuid4()) + '.' + filename.rsplit('.', 1)[1]
            file.save(os.path.join(ADMIN_UPLOAD_FOLDER, file_name))
            file_path = ADMIN_UPLOAD_FOLDER + slash + file_name
            params.is_success = True
            params.msg = '上传成功！'
            params.file_path = file_path
            # 记录
            upload_logger = UploadLog()
            upload_logger.admin_user_id = session.get('admin_user_id')
            upload_logger.file_path = params.file_path.replace(settings.WEB_PB, '')
            # 提交记录
            db: SQLAlchemy = app.db
            try:
                db.session.add(upload_logger)
                db.session.commit()
            except Exception:
                db.session.rollback()
        else:
            params.msg = '不支持的文件拓展：' + file.filename.rsplit('.', 1)[1] + ' 支持的拓展：' + str(ALLOW_EXTENSIONS)
    return params


@pc_login_required
def upload_file(template: str, callback=None):
    """
    前台导入文件
    :param template:
    :param callback:
    :return:
    """

    class params():
        msg = None
        is_success = False

    if request.method == 'POST':
        # 获取post过来的文件名称，从name=file参数中获取
        file = request.files['file']
        if file and allowed_file(file.filename):
            # secure_filename方法会去掉文件名中的中文
            filename = secure_filename(file.filename)
            # 因为上次的文件可能有重名，因此使用uuid保存文件
            file_name = str(uuid.uuid4()) + '.' + filename.rsplit('.', 1)[1]
            file.save(os.path.join(UPLOAD_FOLDER, file_name))
            file_path = UPLOAD_FOLDER + slash + file_name
            print(file_path)
            params.is_success = True
            params.msg = '上传成功！'

            # 处理数据
            file_data = open(file=file_path, mode='r', encoding='UTF-8')
            print(file_data)
            if callback:
                return callback()
        else:
            params.msg = '不支持的文件拓展：' + file.filename.rsplit('.', 1)[1] + ' 支持的拓展：' + str(ALLOW_EXTENSIONS)
    return render_template(template, arg=params)
